package com.sojson.result.interfaces.impl;

import com.sojson.result.interfaces.BeforeBodyWriteInterface;
import com.sojson.util.StringUtil;
import com.sojson.util.encryption.EncryptionUtil;
import com.sojson.util.json.JsonUtil;
import com.sojson.util.servlet.ServletUtil;

/**
 * 只有一个方法,在Controller返回数据前对数据进行操作
 * 
 * @author liu
 * @date 2020-10-06
 */
public class BeforeBodyWriteInterfaceImpl implements BeforeBodyWriteInterface {

    private static BeforeBodyWriteInterfaceImpl beforeBodyWriteInterfaceImpl = null;

    private BeforeBodyWriteInterfaceImpl() {}

    /**
     * 在Controller返回数据前对数据进行操作
     * 
     * @param body 返回的对象
     * @return
     */
    @Override
    public Object BeforeBodyWrite(Object body) {
        String bd = objectToJsonAll(body);

        if (BeforeBodyWriteInterface.JSON_STRING
            .equals(getValRequest(BeforeBodyWriteInterface.RESPONSE_BODY_TYPE_KEY))) {
            return bd;
        } else if (BeforeBodyWriteInterface.JSON_STRING_ENCRYPTION
            .equals(getValRequest(BeforeBodyWriteInterface.RESPONSE_BODY_TYPE_KEY))) {
            return encryptionReversible(bd, BeforeBodyWriteInterface.RESPONSE_DATA_KEY);
        }
        return body;
    }

    /**
     * 判断一个对象是否是空(空对象)
     * 
     * @param obj
     * @return
     */
    private static boolean isBlankObject(Object obj) {
        return StringUtil.isBlankObject(obj);
    }

    /**
     * 从当前的Request里取值
     * 
     * @param key
     * @return
     */
    private Object getValRequest(String key) {
        return ServletUtil.getValRequest(key);
    }

    /**
     * 将对象转换成json字符串(值为空的也解析)
     * 
     * @param data 被转换的对象
     * @return 得到的字符串
     */
    private String objectToJsonAll(Object data) {
        return JsonUtil.objectToJsonAll(data);
    }

    /**
     * 可逆的加密方法
     * 
     * @param inStr
     * @param key 加密密钥
     * @return
     */
    private static String encryptionReversible(String inStr, String key) {
        return EncryptionUtil.encryptionReversible(inStr, key);
    }

    public static BeforeBodyWriteInterfaceImpl getInstances() {
        if (isBlankObject(BeforeBodyWriteInterfaceImpl.beforeBodyWriteInterfaceImpl)) {
            BeforeBodyWriteInterfaceImpl.beforeBodyWriteInterfaceImpl = new BeforeBodyWriteInterfaceImpl();
        }
        return BeforeBodyWriteInterfaceImpl.beforeBodyWriteInterfaceImpl;
    }

}